package com.xyh.concurrency.example.lock;

import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * juc 中的锁
 * ReentrantReadWriteLock 这个锁为读写锁当有读的线程正在进行,写的操作就会一直等待
 */
@Slf4j
public class LockExample3 {
    //私有化读写锁
    private Map<String, Data> map = new TreeMap<>();
    //读写锁
    private final ReadWriteLock lock = new ReentrantReadWriteLock();
    //获取读锁
    private final Lock readLock = lock.readLock();
    //获取写锁
    private final Lock writeLock = lock.writeLock();

    public Data get(String key) {
        try {
            readLock.lock();
            return map.get(key);
        } finally {
            readLock.unlock();
        }

    }

    public Data getAll() {
        try {
            readLock.lock();
            return (Data) map.keySet();
        } finally {
            readLock.unlock();
        }

    }

    public void put(String key, Data data) {

        try {
            writeLock.lock();
            map.put(key, data);
        } finally {
            readLock.unlock();
        }

    }


    class Data {
    }
}
